<template>
	<view class="setting" :class="{ loading: isGlobalLoading }">
		<!-- 加载遮罩 -->
		<view v-if="isLoading" class="loading-overlay">
			<view class="loading-content">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
		</view>

		<view class="box" :class="{ animate: contentLoaded }">
			<!-- 头像上传 -->
			<StepInput :title="'头像'" :require="false" class="mb">
				<button 
					hover-class="button-hover" 
					class="upload_box button" 
					:class="{ uploading: isUploading }"
					open-type="chooseAvatar" 
					@chooseavatar="handleAvatarUpload"
					:disabled="isUploading">
					<image :src="avatarUrl" mode="aspectFill" class="img"></image>
					<view class="btn">
						{{ uploadButtonText }}
					</view>
					<view v-if="isUploading" class="upload-loading">
						<view class="upload-spinner"></view>
					</view>
				</button>
			</StepInput>

			<!-- 昵称输入 -->
			<StepInput :title="'昵称'" :require="false" class="mb">
				<u-input 
					type="nickname" 
					v-model="query.nickname" 
					:border="false" 
					input-align="right" 
					placeholder="请输入昵称" 
					class="input_cs"  
					:clearable="false"
					maxlength="20"
					@input="clearValidationError('nickname')" />
				<image :src="$IMG_URL('/static/home/indicate.png')" mode="aspectFill" class="icon"></image>
			</StepInput>

			<!-- 生日选择 -->
			<StepInput :title="'出生日期'" :require="false" class="mb">
				<u-input 
					type="text" 
					v-model="query.birthday" 
					:border="false" 
					input-align="right" 
					placeholder="请选择出生日期" 
					class="input_cs" 
					disabled
					@click="calendarShow = true"  
					:clearable="false"/>
				<image :src="$IMG_URL('/static/home/indicate.png')" mode="aspectFill" class="icon"></image>
			</StepInput>

			<!-- 性别选择 -->
			<StepInput :title="'性别'" :require="false" class="mb">
				<u-input 
					type="text" 
					:value="genderText" 
					:border="false" 
					input-align="right" 
					placeholder="请选择性别" 
					class="input_cs" 
					disabled
					@click="sexShow = true"  
					:clearable="false"/>
				<image :src="$IMG_URL('/static/home/indicate.png')" mode="aspectFill" class="icon"></image>
			</StepInput>

			<!-- 人生格言 -->
			<view class="comlum_Y mb">
				<view class="left">
					<view class="size">
						人生格言
					</view>
				</view>
				<u-input 
					type="textarea" 
					:border="false" 
					:height="230" 
					:auto-height="false" 
					:custom-style="customStyle"
					placeholder="请填写人生格言" 
					v-model="query.bio"  
					:clearable="false"
					maxlength="200"
					@input="clearValidationError('bio')" />
			</view>
		</view>

		<view class="empty"></view>

		<!-- 底部按钮 -->
		<view class="foot" :class="{ show: contentLoaded }">
			<view 
				class="btn2" 
				:class="{ 
					active: isLogoutActive,
					disabled: isGlobalLoading 
				}"
				@click.stop="handleLogout">
				<text class="btn-text">{{ logoutButtonText }}</text>
				<view v-if="isLogoutActive" class="btn-loading">
					<view class="btn-spinner"></view>
				</view>
			</view>
			<view 
				class="btn1" 
				:class="{ 
					active: canSave && !isSaving,
					disabled: !canSave || isSaving,
					saving: isSaving 
				}"
				@click.stop="handleSave">
				<text class="btn-text">{{ saveButtonText }}</text>
				<view v-if="isSaving" class="btn-loading">
					<view class="btn-spinner"></view>
				</view>
			</view>
		</view>

		<u-toast ref="uToast" />
		
		<!-- 选择器 -->
		<u-picker 
			mode="time" 
			v-model="calendarShow" 
			:params="params" 
			:customTimeTag="true" 
			:title="'选择出生日期'" 
			:popupheight="'786rpx'" 
			:borderRadius="16" 
			@confirm="handleDateConfirm"></u-picker>
		<u-picker  
			v-model="sexShow" 
			mode="selector" 
			:range="sexParams" 
			:customTimeTag="true" 
			:title="'性别'"
			:popupheight="'786rpx'" 
			:borderRadius="16" 
			@confirm="handleGenderConfirm"></u-picker>
	</view>
</template>

<script>
	import StepInput from '../user/become_coach/components/StepInput.vue'
	import popupVue from '@/components/popup.vue'
	import{
		editUser,
		Info
	} from '@/api/user.js'
	export default {
		components: {
			StepInput,
			popupVue
		},
		data() {
			return {
				customStyle: {
					background: '#f6f6f6',
					padding: '32rpx'
				},
				// 性别选项
				sexParams: ['女', '男'],
				// 控制弹窗显示状态
				sexShow: false,
				calendarShow: false,
				// 用户信息
				query: {
					nickname: '',
					avatar: '',
					gender: 0,
					birthday: '',
					bio: ''
				},
				// 原始用户信息（用于对比是否有修改）
				originalQuery: {
					nickname: '',
					avatar: '',
					gender: 0,
					birthday: '',
					bio: ''
				},
				// 加载和操作状态
				isLoading: false,
				isUploading: false,
				isSaving: false,
				contentLoaded: false,
				isLogoutActive: false,
				isSaveActive: false,
				// 表单验证错误
				validationErrors: {},
				// 日期选择器参数
				params: {
					year: true,
					month: true,
					day: true,
					hour: false,
					minute: false,
					second: false
				}
			}
		},
		computed: {
			// 性别文本显示
			genderText() {
				return this.sexParams[this.query.gender] || '请选择性别';
			},
			// 判断是否可以保存
			canSave() {
				// 检查是否有修改
				const hasChanges = JSON.stringify(this.query) !== JSON.stringify(this.originalQuery);
				// 检查必要字段
				const hasNickname = this.query.nickname && this.query.nickname.trim().length > 0;
				// 不在保存状态且有修改且有昵称
				return !this.isSaving && hasChanges && hasNickname;
			},
			// 头像地址
			avatarUrl() {
				return this.query.avatar || this.$IMG_URL('/static/user/default2.png');
			},
			// 保存按钮文本
			saveButtonText() {
				return this.isSaving ? '保存中...' : '保存';
			},
			// 退出按钮文本
			logoutButtonText() {
				return this.isLogoutActive ? '退出中...' : '退出登录';
			},
			// 上传按钮文本
			uploadButtonText() {
				return this.isUploading ? '上传中...' : '重新上传';
			},
			// 全局加载状态
			isGlobalLoading() {
				return this.isLoading || this.isUploading || this.isSaving;
			}
		},
		onLoad() {
			this.initPage();
		},
		onShow() {
			// 页面显示时检查是否需要刷新数据
			if (this.contentLoaded) {
				this.refreshUserInfo();
			}
		},
		methods: {
			// 初始化页面
			async initPage() {
				try {
					this.isLoading = true;
					uni.showLoading({ title: '加载中...' });
					
					await this.getUserInfo();
					this.contentLoaded = true;
					
					// 模拟加载时间，让动画更自然
					setTimeout(() => {
						uni.hideLoading();
					}, 500);
				} catch (error) {
					console.error('初始化页面失败:', error);
					this.showToast('加载失败，请重试', 'error');
				} finally {
					this.isLoading = false;
					uni.hideLoading();
				}
			},

			// 刷新用户信息
			async refreshUserInfo() {
				try {
					await this.getUserInfo();
				} catch (error) {
					console.error('刷新用户信息失败:', error);
				}
			},

			// 获取用户信息
			async getUserInfo() {
				try {
					const { data: res } = await Info();
					console.log('用户信息:', res);
					
					if (res.code === 1) {
						this.query = { ...res.data.userinfo };
						// 保存原始数据用于对比
						this.originalQuery = { ...res.data.userinfo };
						// 清除验证错误
						this.validationErrors = {};
					} else {
						throw new Error(res.msg || '获取用户信息失败');
					}
				} catch (error) {
					console.error('获取用户信息失败:', error);
					throw error;
				}
			},

			// 退出登录
			async handleLogout() {
				if (this.isLogoutActive || this.isGlobalLoading) return;
				
				try {
					const confirmed = await this.showConfirmModal(
						'温馨提示',
						'您即将退出登录，是否继续？请确认。'
					);
					
					if (!confirmed) return;
					
					this.isLogoutActive = true;
					
					// 模拟退出操作延迟
					await new Promise(resolve => setTimeout(resolve, 800));
					
					// 清除用户登录状态
					uni.removeStorageSync('token');
					uni.clearStorageSync();
					
					// 提示用户已退出
					this.showToast('退出登录成功', 'success');
					
					// 发送退出事件
					uni.$emit('loginOut');
					
					// 返回上一页
					setTimeout(() => {
						uni.navigateBack({ delta: 1 });
					}, 1000);
					
				} catch (error) {
					console.error('退出登录失败:', error);
					this.showToast('退出失败，请重试', 'error');
				} finally {
					this.isLogoutActive = false;
				}
			},

			// 保存用户信息
			async handleSave() {
				if (!this.canSave) return;
				
				try {
					// 表单验证
					if (!this.validateForm()) {
						return;
					}
					
					this.isSaving = true;
					uni.showLoading({ title: '保存中...' });
					
					const { data: res } = await editUser(this.query);
					
					if (res.code === 1) {
						// 更新原始数据
						this.originalQuery = { ...this.query };
						this.showToast(res.msg || '保存成功', 'success', true);
					} else {
						throw new Error(res.msg || '保存失败');
					}
					
				} catch (error) {
					console.error('保存用户信息失败:', error);
					this.showToast(error.message || '保存失败，请重试', 'error');
				} finally {
					this.isSaving = false;
					uni.hideLoading();
				}
			},

			// 上传头像
			async handleAvatarUpload(e) {
				if (this.isUploading) return;
				
				try {
					this.isUploading = true;
					uni.showLoading({ title: '上传中...' });
					
					let avatarUrl = '';
					
					if (e.detail.avatarUrl) {
						// 微信头像选择
						avatarUrl = await this.$UPLOADIMAGE(e.detail.avatarUrl, 'apply');
					} else {
						// 相册/相机选择
						const chooseResult = await this.chooseImageFromAlbum();
						if (chooseResult) {
							avatarUrl = await this.$UPLOADIMAGE(chooseResult, 'apply');
						}
					}
					
					if (avatarUrl) {
						this.query.avatar = avatarUrl;
						this.showToast('头像上传成功', 'success');
					}
					
				} catch (error) {
					console.error('上传头像失败:', error);
					this.showToast('上传失败，请重试', 'error');
				} finally {
					this.isUploading = false;
					uni.hideLoading();
				}
			},

			// 从相册选择图片
			chooseImageFromAlbum() {
				return new Promise((resolve, reject) => {
					uni.chooseImage({
						count: 1,
						sizeType: ['original'],
						sourceType: ['album', 'camera'],
						success: (res) => {
							resolve(res.tempFilePaths[0]);
						},
						fail: reject
					});
				});
			},

			// 日期确认
			handleDateConfirm(e) {
				try {
					console.log('日期选择结果:', e);
					this.query.birthday = `${e.year}-${e.month}-${e.day}`;
					this.calendarShow = false;
				} catch (error) {
					console.error('日期设置失败:', error);
					this.showToast('日期设置失败', 'error');
				}
			},

			// 性别选择确认
			handleGenderConfirm(e) {
				try {
					console.log('性别选择结果:', e);
					this.query.gender = e[0];
					this.sexShow = false;
				} catch (error) {
					console.error('性别设置失败:', error);
					this.showToast('性别设置失败', 'error');
				}
			},

			// 清除验证错误
			clearValidationError(field) {
				if (this.validationErrors[field]) {
					this.$delete(this.validationErrors, field);
				}
			},

			// 表单验证
			validateForm() {
				this.validationErrors = {};
				
				// 昵称验证
				if (!this.query.nickname || this.query.nickname.trim().length === 0) {
					this.validationErrors.nickname = '请输入昵称';
				} else if (this.query.nickname.trim().length > 20) {
					this.validationErrors.nickname = '昵称不能超过20个字符';
				}
				
				// 人生格言验证
				if (this.query.bio && this.query.bio.length > 200) {
					this.validationErrors.bio = '人生格言不能超过200个字符';
				}
				
				// 显示验证错误
				const errorKeys = Object.keys(this.validationErrors);
				if (errorKeys.length > 0) {
					const firstError = this.validationErrors[errorKeys[0]];
					this.showToast(firstError, 'error');
					return false;
				}
				
				return true;
			},

			// 显示提示消息
			showToast(title, type = 'none', back = false) {
				if (this.$refs.uToast) {
					this.$refs.uToast.show({
						title,
						type,
						icon: false,
						back
					});
				} else {
					uni.showToast({
						title,
						icon: type === 'success' ? 'success' : 'none'
					});
				}
			},

			// 显示确认框
			showConfirmModal(title, content) {
				return new Promise((resolve) => {
					uni.showModal({
						title,
						content,
						confirmColor: '#73F0EA',
						success: (res) => {
							resolve(res.confirm);
						},
						fail: () => {
							resolve(false);
						}
					});
				});
			},

			// ==== 以下为兼容旧方法（逐步迁移） ====
			// 退出登录（旧方法）
			loginOut() {
				this.handleLogout();
			},

			// 保存用户信息（旧方法）
			geteditUser() {
				this.handleSave();
			},

			// 获取用户信息（旧方法）
			getInfo() {
				this.getUserInfo();
			},

			// 查找性别（旧方法）
			findSex(list, data) {
				return list[data] || '请选择性别';
			},

			// 上传头像（旧方法）
			chooseImg(e) {
				this.handleAvatarUpload(e);
			},

			// 日期确认（旧方法）
			dateConfirm(e) {
				this.handleDateConfirm(e);
			},

			// 性别选择（旧方法）
			changeSex(e) {
				this.handleGenderConfirm(e);
			},

			// 其他旧方法兼容处理
			openNickName() {
				// 如果需要可以在这里实现昵称编辑逻辑
			},
			calendarClose() {
				this.calendarShow = false;
			},
			calendarSure() {
				this.calendarShow = false;
			},
			bindDateChange(e) {
				console.log('日期变化:', e.detail.value);
			},
			sexSure() {
				this.sexShow = false;
			},
			sexClose() {
				this.sexShow = false;
			}
		}
	}
</script>

<style lang="scss">
	.empty {
		width: 750rpx;
		height: 180rpx;
	}

	button {
		margin: unset;
		padding: unset;
		background-color: transparent;
		/* 消除背景色 */
		border: none;
		/* 消除边框 */
	}

	button:after {
		border: unset;
	}

	page {
		background: #e9e9e9;
	}

	.icon {
		width: 10rpx;
		height: 16rpx;
		margin-left: 8rpx;
	}

	.comlum_Y {
		display: flex;
		flex-direction: column;
		width: 622rpx;

	}

	.left {
		display: flex;
		flex-direction: row;
		flex: 1;
		margin-bottom: 24rpx;

		.star {
			font-size: 28rpx;
			font-family: PingFang SC, PingFang SC-Bold;
			font-weight: 700;
			text-align: left;
			color: #f37364;
		}

		.size {
			font-size: 28rpx;
			font-family: PingFang SC, PingFang SC-Bold;
			font-weight: 700;
			text-align: left;
			color: #333333;
		}
	}

	.setting {
		display: flex;
		flex-direction: column;
		align-items: center;

		.box {
			margin-top: 32rpx;
			width: 702rpx;
			background: #ffffff;
			border-radius: 16rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			padding: 40rpx;

			.mb {
				margin-bottom: 48rpx;
			}

			.upload_box {
				width: 204rpx;
				height: 204rpx;
				border-radius: 16rpx;
				position: relative;
				overflow: hidden;

				padding: 0;

				.img {
					width: 100%;
					height: 100%;
				}

				.btn {
					position: absolute;
					bottom: 0;
					width: 204rpx;
					height: 46rpx;
					background: rgba(102, 102, 102, 0.8);
					border-radius: 0rpx 0rpx 16rpx 16rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					font-family: PingFang SC, PingFang SC-Medium;
					font-weight: 500;
					color: #ffffff;
				}
			}
		}
	}

	.foot {
		position: fixed;
		bottom: 0;
		padding-top: 10rpx;
		width: 750rpx;
		height: 160rpx;
		background: #ffffff;
		box-shadow: 0rpx 8rpx 28rpx 0rpx rgba(166, 179, 194, 0.30);
		display: flex;
		justify-content: center;

		.btn1 {
			width: 346rpx;
			height: 88rpx;
			background: #73F0EA;
			border-radius: 16rpx;
			font-size: 34rpx;
			font-family: PingFang SC, PingFang SC-Bold;
			font-weight: 700;
			color: #ffffff;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		.btn2{
			margin-right: 18rpx;
			width: 346rpx;
			height: 88rpx;
			border-radius: 16rpx;
			font-size: 34rpx;
			font-family: PingFang SC, PingFang SC-Bold;
			font-weight: 700;
			color: #73F0EA;
			border: #73F0EA 1rpx solid;
			display: flex;
			align-items: center;
			justify-content: center;
		}
	}

	.time-comlum-box {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	}

	// 加载状态
	.loading-overlay {
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: rgba(255, 255, 255, 0.9);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 9999;
		backdrop-filter: blur(10rpx);

		.loading-content {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.loading-spinner {
				width: 60rpx;
				height: 60rpx;
				border: 4rpx solid #f3f3f3;
				border-top: 4rpx solid #73F0EA;
				border-radius: 50%;
				animation: spin 1s linear infinite;
				margin-bottom: 20rpx;
			}
			
			.loading-text {
				font-size: 28rpx;
				color: #666;
			}
		}
	}

	// 页面动画
	.setting {
		transition: all 0.3s ease;
		
		&.loading {
			filter: blur(2rpx);
		}
		
		.box {
			transform: translateY(40rpx);
			opacity: 0;
			transition: all 0.6s cubic-bezier(0.4, 0, 0.2, 1);
			
			&.animate {
				transform: translateY(0);
				opacity: 1;
			}
		}
	}

	// 按钮状态
	.upload_box {
		position: relative;
		transition: all 0.3s ease;
		
		&.uploading {
			.img {
				filter: brightness(0.7);
			}
		}
		
		.upload-loading {
			position: absolute;
			top: 50%;
			left: 50%;
			transform: translate(-50%, -50%);
			
			.upload-spinner {
				width: 40rpx;
				height: 40rpx;
				border: 3rpx solid rgba(255, 255, 255, 0.3);
				border-top: 3rpx solid #73F0EA;
				border-radius: 50%;
				animation: spin 1s linear infinite;
			}
		}
		
		&:active {
			transform: scale(0.98);
		}
	}

	.button-hover {
		transform: scale(0.95);
		transition: transform 0.1s ease;
	}

	// 底部按钮动画
	.foot {
		transform: translateY(100%);
		opacity: 0;
		transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
		
		&.show {
			transform: translateY(0);
			opacity: 1;
		}
		
		.btn1, .btn2 {
			position: relative;
			transition: all 0.3s ease;
			overflow: hidden;
			
			&:active {
				transform: scale(0.98);
			}
			
			&.disabled {
				opacity: 0.6;
				pointer-events: none;
			}
			
			&.active:not(.disabled) {
				transform: scale(1.02);
				box-shadow: 0 6rpx 20rpx rgba(115, 240, 234, 0.4);
			}
			
			&.saving {
				.btn-text {
					opacity: 0.7;
				}
			}
			
			.btn-loading {
				position: absolute;
				right: 20rpx;
				top: 50%;
				transform: translateY(-50%);
				
				.btn-spinner {
					width: 30rpx;
					height: 30rpx;
					border: 2rpx solid rgba(255, 255, 255, 0.3);
					border-top: 2rpx solid #ffffff;
					border-radius: 50%;
					animation: spin 1s linear infinite;
				}
			}
			
			.btn-text {
				transition: opacity 0.3s ease;
			}
		}
		
		.btn2 {
			&.active {
				background: #ff6b6b;
				color: #ffffff;
				border-color: #ff6b6b;
				
				.btn-loading .btn-spinner {
					border-top-color: #ffffff;
				}
			}
		}
	}

	// 输入框焦点效果
	.input_cs {
		transition: all 0.3s ease;
		
		&:focus {
			background: rgba(115, 240, 234, 0.05);
		}
	}

	// 旋转动画
	@keyframes spin {
		0% { transform: rotate(0deg); }
		100% { transform: rotate(360deg); }
	}

	// 渐入动画
	@keyframes fadeInUp {
		0% {
			opacity: 0;
			transform: translateY(30rpx);
		}
		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}
	
</style>